<?php

/*
 * 
 * 
 * 投票的入口
 * 
 * 1. 首页列表产品
 * 
 * 2. 进入指定产品
 * 
 * 3. 分享产品的文案
 */

namespace Home\Controller;

use Think\Controller;

class WidgetvoteController extends CommonController {
    /*
     * 首页
     */

    public function topic() {

        if (IS_AJAX) {
            
        } else {
            $vid = I("get.vid");
            $mid = I("get.mid");

            $url_source = $_SERVER['REQUEST_URI'];
            //判断是否有两个问号

            $flag = strpos($url_source, "??");

            if ($flag) {
                $new_flag = strpos($url_source, "?mid");
                if (!$new_flag) {
                    
                } else {
                    $new_url1 = substr($url_source, 0, $new_flag - 1);

                    $new_url2 = substr($url_source, $new_flag);

                    $new_url = $new_url1 . $new_url2;
                    redirect($new_url);
                }
            }

            /*
             * 记录访问日记
             */
            $fp = fopen("view" . CONTROLLER_NAME . "_" . ACTION_NAME . ".json", "a+");
            fwrite($fp, date("Y-m-d H:i:s") . "vid: $vid; mid $mid,--" . $_SERVER['REQUEST_URI'] . "\n");
            fclose($fp);




//            一次性加载所有系列的的产品
            $vote_topic_res = M("widget_vote_topics")->find($vid);


            $map['vid'] = $vid;
            $map['ishidden'] = 0;
            $products = M("widget_vote_products")->where($map)->order("votes DESC,vote_num ASC")->limit(100)->select();
//            $test['aa']=($products);
//            $new_products = $this->array_sort($products, 'votes', 1);

            $new_products = $products;

//            for($i=1;$i<count($new_products);$i++)
//            {
//                if($new_products[$i]['votes']==$new_products[$i-1]['votes'])
//                {
//                    if($new_products[$i]['vote_num']>$new_products[$i-1]['vote_num'])
//                    {
////                        echo $i."<br/>";
//                        $tmp = $new_products[$i-1];
//                        $new_products[$i-1] = $new_products[$i];
//                        $new_products[$i] = $tmp;
//                    }
//                }
//            }
//            
//            print_r(json_encode($new_products));
//            exit();
//            print_r($new_products);
//            foreach ($products as $key => $value) {
//                //对产品根据 votes 进行排序
//            }
            $this->assign("topic", $vote_topic_res); //投票专题内容
            $this->assign("products", $new_products); //所有可以投票的产品
            $this->assign("topic_count", count($new_products));

            $this->assign("mid", $mid);



            $this->display();
        }
    }

    public function topic_wechat() {

        if (IS_AJAX) {
            
        } else {
            

            $vid = I("get.vid");


//            一次性加载所有系列的的产品
            $vote_topic_res = M("widget_vote_topics")->find($vid);
            unset($vote_topic_res['rules']);


            $map['vid'] = $vid;
            $map['ishidden'] = 0;
//            $products = M("widget_vote_products")->where($map)->order("vote_num ASC")->select();
            $products = M("widget_vote_products")->where($map)->order("votes DESC,vote_num ASC")->select();

//            $new_products = $this->array_sort($products, 'votes', 1);
            $new_products = $products;
//            foreach ($products as $key => $value) {
//                //对产品根据 votes 进行排序
//            }
            $this->assign("topic", $vote_topic_res); //投票专题内容
            $this->assign("products", $new_products); //所有可以投票的产品
            $this->assign("topic_count", count($new_products));

            $mid = session("mid");
            $this->assign("mid", $mid);

            /*
             * 计算微信的分享页面
             */
            $wx_share['title'] = "东方韵【中国丽人秀·深圳站】微信投票火热进行中！";
            $wx_share['desc'] = "引领时代美丽前沿，展特区女性风貌，让我们相约东方韵，遇见最美的自己";
            $wx_share['logo'] = $this->site_url . "/share_logo.png";
            $wx_share['link'] = "http://" . I('server.HTTP_HOST') . "/" . U('Home/Widgetvote/topic_wechat', array('vid' => 1));

            $wx_share['timeline_title'] = "东方韵【中国丽人秀·深圳站】微信投票火热进行中！";

            $this->assign("wx_share", $wx_share);
            
            /*
             * 记录访问
             */
            $fp = fopen("view_topic_wechat_log.json", "a+");
            fwrite($fp, date("Y-m-d H:i:s"). "-- mid: $mid"  . "\n");
            fclose($fp);
            
            
            $this->display();
        }
    }

    /*
     * 搜索页面
     */

    public function search() {
        if (IS_POST) {
            $keywords = I("post.keywords");

            if (preg_match("/^\d*$/", $keywords)) {
                //用户输入的是编号
                $map['vote_num'] = array("like", "%$keywords%");
                ;
            } else {
                $map['name'] = array("like", "%$keywords%");
            }
            $map['ishidden'] = 0;

            $products = M("widget_vote_products")->where($map)->select();

            $new_products = $this->array_sort($products, 'votes', 1);

            $this->assign("products", $new_products); //所有可以投票的产品
            $this->assign("keywords", $keywords);

            /*
             * 计算微信的分享页面
             */
            $wx_share['title'] = "东方韵【中国丽人秀·深圳站】微信投票火热进行中！";
            $wx_share['desc'] = "引领时代美丽前沿，展特区女性风貌，让我们相约东方韵，遇见最美的自己";
            $wx_share['logo'] = $this->site_url . "/share_logo.png";
            $wx_share['link'] = "http://" . I('server.HTTP_HOST') . "/" . U('Home/Widgetvote/topic_wechat', array('vid' => 1));

            $wx_share['timeline_title'] = "东方韵【中国丽人秀·深圳站】微信投票火热进行中！";

            $this->assign("wx_share", $wx_share);
            $mid = session("mid");
            $this->assign("mid", $mid);
            $this->display();
        } else {
            $this->display();
        }
    }
    
    /*
     * 活动规则
     */
    public function rules() {
        $vid = I("get.vid");
        $vote_topic_res = M("widget_vote_topics")->find($vid);
        
        $this->assign("vote_topic",$vote_topic_res);
        
        /*
             * 计算微信的分享页面
             */
            $wx_share['title'] = "东方韵【中国丽人秀·深圳站】微信投票火热进行中！";
            $wx_share['desc'] = "引领时代美丽前沿，展特区女性风貌，让我们相约东方韵，遇见最美的自己";
            $wx_share['logo'] = $this->site_url . "/share_logo.png";
            $wx_share['link'] = "http://" . I('server.HTTP_HOST') . "/" . U('Home/Widgetvote/topic_wechat', array('vid' => 1));

            $wx_share['timeline_title'] = "东方韵【中国丽人秀·深圳站】微信投票火热进行中！";

            $this->assign("wx_share", $wx_share);
            
        $this->display();
        
    }

    /*
     * 详情页
     */

    public function detail() {
        if (IS_AJAX) {
//            获取投票记录输出
            $pid = I("get.pid");
            $pagecount = I("get.pagecount");

            $DB_share = M("widget_vote_records");

            $map['pid'] = $pid;
            $product_vote = $DB_share->where($map)->limit(10)->order("id desc")->select();

            echo json_encode($product_vote);
        } else {
            $pid = I("get.pid");
            $product = M("widget_vote_products")->find($pid);

            $DB_share = M("widget_vote_records");

            $map['fd_widget_vote_records.pid'] = $pid;
            $product_votes = $DB_share->where($map)
                            ->field("fd_widget_vote_records.*,fd_members.avatar,fd_members.username")
                            ->join("left join fd_members ON fd_members.id = fd_widget_vote_records.mid")
                            ->order("fd_widget_vote_records.id desc")
                            ->limit(10)->select();
//            echo $DB_share->getLastSql();
//            获取产品的信息?
            $this->assign("product", $product);
            $this->assign("votes", $product_votes);

            $mid = I("get.mid");
            $this->assign("mid", $mid);

            /*
             * 通过 vid 获取 tips
             */
            $tips = M("widget_vote_topics")->where(array('vid' => $product['vid']))->getField("remarks");
            $this->assign("remarks", $tips);
            /*
             * 计算分享的链接
             * appcall://{"b_type":3,"url":"http://test.zhongcetianxia.com/index.php/Api/V10/Banner/share_demo","toaction":101,"totype":0,"toid":0}
             * 
             */
            $url = "http://" . I('server.HTTP_HOST') . "/" . U('Api/V10/Banner/product_vote_share', array('mid' => $mid, 'pid' => $pid, 'vid' => $product['vid']));

            $appcall_str = 'appcall://{"b_type":3,"url":"' . $url . '?","toaction":0,"totype":0,"toid":0}';

            $this->assign("appcall_str", $appcall_str);


            /*
             * 获取传递过来的 rank
             */
            $this->assign("ranks", I("get.ranks"));


            $this->display();
        }
    }

    public function detail_wechat() {
        if (IS_AJAX) {
//            获取投票记录输出
            $pid = I("get.pid");
            $pagecount = I("get.pagecount");

            $DB_share = M("widget_vote_records");

            $map['pid'] = $pid;
            $product_vote = $DB_share->where($map)->limit(10)->order("id desc")->select();

            echo json_encode($product_vote);
        } else {
            $pid = I("get.pid");
            $product = M("widget_vote_products")->find($pid);

            $DB_share = M("widget_vote_records");

            $map['fd_widget_vote_records.pid'] = $pid;
            $product_votes = $DB_share->where($map)
                            ->field("fd_widget_vote_records.*,fd_members.avatar,fd_members.username")
                            ->join("left join fd_members ON fd_members.id = fd_widget_vote_records.mid")
                            ->order("fd_widget_vote_records.id desc")->limit(10)->select();
//            echo $DB_share->getLastSql();
//            获取产品的信息?
            $this->assign("product", $product);
            $this->assign("votes", $product_votes);

            $mid = session("mid");
            $this->assign("mid", $mid);

            /*
             * 通过 vid 获取 tips
             */
            $tips = M("widget_vote_topics")->where(array('vid' => $product['vid']))->getField("remarks");
            $this->assign("remarks", $tips);

            /*
             * 计算分享的链接
             * appcall://{"b_type":3,"url":"http://test.zhongcetianxia.com/index.php/Api/V10/Banner/share_demo","toaction":101,"totype":0,"toid":0}
             * 
             */
            $url = "http://" . I('server.HTTP_HOST') . "/" . U('Api/V10/Banner/product_vote_share', array('mid' => $mid, 'pid' => $pid, 'vid' => $product['vid']));

            $appcall_str = 'appcall://{"b_type":3,"url":"' . $url . '?","toaction":0,"totype":0,"toid":0}';

            $this->assign("appcall_str", $appcall_str);


            /*
             * 计算微信的分享页面
             */
            $wx_share['title'] = "东方韵【中国丽人秀·深圳站】微信投票火热进行中！";
            $wx_share['desc'] = "引领时代美丽前沿，展特区女性风貌，让我们相约东方韵，遇见最美的自己";
            $wx_share['logo'] = $this->site_url . "/share_logo.png";
            $wx_share['link'] = "http://" . I('server.HTTP_HOST') . "/" . U('Home/Widgetvote/topic_wechat', array('vid' => 1));

            $wx_share['timeline_title'] = "东方韵【中国丽人秀·深圳站】微信投票火热进行中！";

            $this->assign("wx_share", $wx_share);

            /*
             * 获取传递过来的 rank
             */
            $this->assign("ranks", I("get.ranks"));


            $this->display();
        }
    }

    /*
     * 投票
     * 
     * 投票分为几个情况，是否投票过
     * 
     */

    public function vote_it() {

        $vid = I("post.vid");
        $pid = I("post.pid");
        $mid = I("post.mid");
        
        /*
         * 判断总票数
         * 500+ 不可投票
         */
        
        $today_date = date("Ymd");
        $map_chk['cdate'] = $today_date;
        $map_chk['pid'] = $pid;
        $pid_count = $DB->where($map)->count();
        if ($pid_count >= 500) {
            $res['err'] = 9;
            echo json_encode($res);
            exit();
        }
        
        

//        判断今天是否有投票过
        $map['cdate'] = $today_date;
        $map['mid'] = $mid;
        $DB = M("widget_vote_records");
        /*
         * 一天最多投票20次
         */
        $today_count = $DB->where($map)->count();

        if ($today_count >= 1) {
            $res['err'] = 1;
            echo json_encode($res);
            exit();
        }


        $map['vid'] = $vid;
        $map['pid'] = $pid;

//        $map['cdate'] = $today_date;


        $result = $DB->where($map)->find();

        if (empty($result)) {
//            没有记录，可以成功投票
            $data['vid'] = $vid;
            $data['pid'] = $pid;
            $data['mid'] = $mid;
            $data['cdate'] = $today_date;
            $data['ctime'] = NOW_TIME;
            $data['ip'] = $_SERVER["REMOTE_ADDR"];

            $id = $DB->add($data);

            if ($id) {
//                添加票数
                M("widget_vote_products")->where("pid=" . $pid)->setInc("votes");
                $res['err'] = 0;

                //增加 voters_count
                M("widget_vote_topics")->where("vid=" . $vid)->setInc("voters_count");
            } else {
                $res['err'] = 1;
            }
        } else {
//            有记录，不可以投票
            $res['err'] = 1;
        }




        echo json_encode($res);
    }

    /*
     * 分享请求页面
     */


    /*
     * 二维数组排序算法函数
     * 排序方法
     * 二维数组排序， $arr是数据，$keys是排序的健值，$order是排序规则，1是升序，0是降序
     */

    public function array_sort($arr, $keys, $order = 0) {
        if (!is_array($arr)) {
            return false;
        }
        $keysvalue = array();
        foreach ($arr as $key => $val) {
            $keysvalue[$key] = $val[$keys];
        }
        if ($order == 0) {
            asort($keysvalue);
        } else {
            arsort($keysvalue);
        }
        reset($keysvalue);
        foreach ($keysvalue as $key => $vals) {
            $keysort[$key] = $key;
        }
        $new_array = array();
        foreach ($keysort as $key => $val) {
            $new_array[$key] = $arr[$val];
        }
        return $new_array;
    }

    public function test() {
        $fruits = array("d" => "lemon", "a" => "lemon", "b" => "lemon", "c" => "lemon");
        arsort($fruits);
        print_r($fruits);
    }

}
